<?php

namespace app\admin\service\auth;

use app\common\cache\AdminAuthCache;
use tmcore\base\BaseService;
use app\common\enum\YesNoEnum;
use app\common\model\auth\Admin;
use app\common\model\auth\SystemMenu;
use app\common\model\auth\SystemRoleMenu;
use think\helper\Str;


/**
 * 系统菜单服务类
 */
class MenuService extends BaseService
{
    /**
     * 获取菜单列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getList() {

        $searchParam = [
            'in' => ['type@type'],
        ];
        $where = self::getSearchData($searchParam);

        $lists = SystemMenu::where($where)->order(['sort' => 'desc', 'id' => 'asc'])
            ->append(['disable_desc'])
            ->select()
            ->toArray();
        return linear_to_tree($lists, 'children');
    }

    /**
     * 获取管理员对应的角色菜单
     * @param $adminId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getMenuByAdminId($adminId)
    {
        $admin = Admin::findOrEmpty($adminId);

        $where = [];
        $where[] = ['type', 'in', ['M', 'C']];
        $where[] = ['is_disable', '=', 0];

        if ($admin['root'] != 1) {
            $roleMenu = SystemRoleMenu::whereIn('role_id', $admin['role_id'])->column('menu_id');
            $where[] = ['id', 'in', $roleMenu];
        }

        $menus = SystemMenu::where($where)
            ->order(['sort' => 'desc', 'id' => 'asc'])
            ->select()->toArray();

        $datas = [];
        foreach ($menus as $item){
            foreach ($item as $key => $val) {
                $name = Str::camel($key);
                if ($name !== $key) {
                    $item[$name] = $val;
                    unset($item[$key]);
                }
            }
            $datas[] = $item;
        }

        return $datas;
    }

    /**
     * 添加菜单
     * @param array $params
     * @return bool
     */
    public static function add(array $params)
    {
        $res = SystemMenu::add([
            'pid' => $params['pid'],
            'type' => $params['type'],
            'name' => $params['name'],
            'icon' => $params['icon'] ?? '',
            'sort' => $params['sort'],
            'perms' => $params['perms'] ?? '',
            'paths' => $params['paths'] ?? '',
            'component' => $params['component'] ?? '',
            'selected' => $params['selected'] ?? '',
            'params' => $params['params'] ?? '',
            'is_keep_alive' => $params['is_keep_alive'],
            'is_link' => $params['is_link'],
            'link_url' => $params['link_url'] ?? '',
            'is_iframe' => $params['is_iframe'],
            'is_hide' => $params['is_hide'],
            'is_affix' => $params['is_affix'],
            'is_disable' => $params['is_disable'],
            'addon' => '',
        ]);
        // 检验权限缓存
        if($res) (new AdminAuthCache)->checkAuthChange();
        return $res;
    }


    /**
     * 编辑菜单
     * @param array $params
     * @return bool
     */
    public static function edit(array $params)
    {
        $res = SystemMenu::edit([
            'pid' => $params['pid'],
            'type' => $params['type'],
            'name' => $params['name'],
            'icon' => $params['icon'] ?? '',
            'sort' => $params['sort'],
            'perms' => $params['perms'] ?? '',
            'paths' => $params['paths'] ?? '',
            'component' => $params['component'] ?? '',
            'selected' => $params['selected'] ?? '',
            'params' => $params['params'] ?? '',
            'is_keep_alive' => $params['is_keep_alive'],
            'is_link' => $params['is_link'],
            'link_url' => $params['link_url'] ?? '',
            'is_iframe' => $params['is_iframe'],
            'is_hide' => $params['is_hide'],
            'is_affix' => $params['is_affix'],
            'is_disable' => $params['is_disable']
        ], $params['id']);
        // 检验权限缓存
        if($res)(new AdminAuthCache)->checkAuthChange();
        return $res;
    }


    /**
     * 详情
     * @param $params
     * @return array
     */
    public static function detail($params)
    {
        return SystemMenu::findOrEmpty($params['id'])->toArray();
    }


    /**
     * 删除菜单
     * @param $params
     * @return bool
     */
    public static function delete($params)
    {
        self::beginTrans();
        try {
            // 删除菜单
            $res = SystemMenu::del($params['id']);
            if(!$res) throw new \Exception('删除菜单失败');

            // 删除角色-菜单表中 与该菜单关联的记录
            SystemRoleMenu::where(['menu_id' => $params['id']])->delete();

            self::commitTrans();
            // 检验权限缓存
            (new AdminAuthCache)->checkAuthChange();
            return true;
        } catch (\Exception $e) {
            self::rollbackTrans();
            return self::setError($e->getMessage());
        }
    }

    /**
     * 全部数据
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAllData()
    {
        $data = SystemMenu::where(['is_disable' => YesNoEnum::NO])
            ->field('id,pid,name')
            ->order(['sort' => 'desc', 'id' => 'desc'])
            ->select()
            ->toArray();

        return linear_to_tree($data, 'children');
    }

    /**
     * 获取管理员对应的权限数据
     * @param $adminId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAuthByAdminId($adminId)
    {
        $admin = Admin::findOrEmpty($adminId);

        $where = [];
        $where[] = ['type', 'in', ['A']];
        $where[] = ['is_disable', '=', 0];

        if ($admin['root'] != 1) {
            $roleMenu = SystemRoleMenu::whereIn('role_id', $admin['role_id'])->column('menu_id');
            $where[] = ['id', 'in', $roleMenu];
        }

        $permsList = SystemMenu::where($where)
            ->order(['sort' => 'desc', 'id' => 'asc'])
            ->column('perms');

        return ['authBtnList' => $permsList];
    }

}